/**
 * 注册、登录、注销
 * */
import util from '@/libs/util';
import router from '@/router';
import store from '@/store/index';
import { Modal } from 'view-design';
import {SystemLogout} from "@/api/system/login";
import {AccountInit} from "../../../api/system/account";
export default {
    namespaced: true,
    actions: {
        /**
         * @description 退出登录
         * */
        logout ({ commit, dispatch }, { confirm = false, vm } = {}) {

            async function logout () {
              SystemLogout().then((res) => {
                  if(res.code == 200) {
                      localStorage.clear();
                      util.cookies.remove('system_token')
                      util.cookies.remove('system_expires_time')
                      util.cookies.remove('system_uuid')
                      // 删除localStorage
                      store.dispatch('pub/db/databaseClear', {
                        user: true
                      });
                      //清空 路由记录
                    //  store.dispatch('system/page/closeAll',{}, {root: true});
                      // 清空 vuex 用户信息
                      dispatch('system/user/set', {}, {root: true});
                    // 跳转路由
                    router.push({ name: 'system_login'});
                  }
                }).catch(() => {
                  //  Modal.$alert("退出失败");
                })
            }
            if (confirm) {
                Modal.confirm({
                    title: "系统提示",
                    content: "你确定要退出吗？",
                    onOk () {
                        logout();
                    }
                });
            } else {
                logout();
            }
        },
        /**
         * @description 用户登录后从持久化数据加载一系列的设置
         * @param {Object} state vuex state
         * @param {Object} dispatch vuex dispatch
         */
        load ({ state, dispatch }) {
          //获取最新数据
          AccountInit().then(res => {
              if(res.code == 200) {
                store.dispatch('system/menu/set', res.data.menus);
                store.dispatch('system/user/setpaths',res.data.paths);
                store.dispatch('system/user/set', res.data.user_info);
              }
            }).catch(err=>{
              console.log(err);
            });
            return new Promise(async resolve => {
                // 加载用户登录信息
                await dispatch('system/user/load', null, { root: true });
                // 持久化数据加载上次退出时的多页列表
                await dispatch('system/page/openedLoad', null, { root: true });
                //菜单加载
                await dispatch('system/menu/load',null,{root:true});
                // end
                resolve();
            });
        }
    }
};
